package xyc.sjxy.controller;

import xyc.sjxy.common.Result;
import xyc.sjxy.pojo.Users;
import xyc.sjxy.service.UserServices;
import xyc.sjxy.service.impl.UserServicesImpl;
import xyc.sjxy.servlet.BaseServlet;
import xyc.sjxy.utils.JsonUtils;
import xyc.sjxy.utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/*")  // /api/13 /api/login /api/reg --》 /13 /login /reg   就是访问路径的参数  /api/a/b/123
public class LoginController extends BaseServlet {
    private UserServices userServices = new UserServicesImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        System.out.println("\"login\" = " + "login");
        //1、获取请求体
        //2、转换为对象
        Users user = JsonUtils.readJson(req, Users.class);
        //3、调用service
        Boolean flag = userServices.validate(user.getUsername(), user.getPassword());
        //4、登录成功
        if (flag) {
            // 4.1将登录状态存储到redis中或者以token的形式发送客户端的localstore（永久持久化了，时间可以自己设置的）
            String token = JwtUtils.createJwt(user.getUsername(), user.getPassword());
            // 4.2、响应
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            JsonUtils.WriteJson(Result.builder(tokenMap, 0, "登录成功！！",true), resp);
        }else{
            //5、登录失败
            //5.1 响应登录失败的信息  业务逻辑应该是转到登录页面（不是由后台完成，由前端程序完成）
            JsonUtils.WriteJson(Result.builder(null, 1, "登录失败！！",false),resp);
        }

    }

    public void reg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        StringBuilder stringBuffer = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
        }
        //{"username":"test01","password":"123456","repassword":"123456"}===》Users(username,password)
        Users t = JsonUtils.toObject(stringBuffer.toString(), Users.class);
        int count = userServices.add(t);
        System.out.println("stringBuffer.toString() = " + stringBuffer.toString());

        JsonUtils.WriteJson(Result.ok(null), resp);// 响应体：json
        /*
        请求体：json
            {
              "username": "lidongxu",
              "password": "111111",
              "repassword": "111111"
            }
         响应体：json
         {
              "code": 0,
              "message": "注册成功！"
         }
        */
    }


}
